import React, { useEffect, useState } from 'react';
import { Outlet, useParams } from 'react-router-dom';
import alert from '../utils/alert';
import client from '../utils/client';
import { delCookie, getCookie, setCookie } from '../utils/cookie';
import { Watermark } from 'antd';

export const SessionContext = React.createContext();

// 处理cookie中的会话令牌
let cookie_token = getCookie('mp.token');
delCookie('mp.token');
if (cookie_token && !client.has('TOKEN')) {
  client.set('TOKEN', cookie_token);
}

// 处理URL中的会话令牌和fragment信息
const urlParams = new URLSearchParams(window.location.search);
const fragment = urlParams.get('fragment');
const token = urlParams.get('access_token');
if (token && !client.has('TOKEN')) {
  client.set('TOKEN', token);
}
if (fragment) {
  window.location.href += `#${fragment}`;
}

function Session({ loginComponent: Login, children }) {
  const [passed, setPassed] = useState(null);
  const { sys } = useParams();

  useEffect(() => {
    (async () => {
      // 加载子系统信息
      try {
        let info = await client.job('B.SystemInfoGet', { Code: sys, });
        client.set('system', info);
      } catch (e) {
        alert('错误', e.message, { type: 'error' });
      }
      // 更新页面状态
      if (client.has('TOKEN')) {
        client.login().then(load_user_info).catch(() => {
          client.set('TOKEN', undefined);
          setPassed(false);
        });
      } else {
        setPassed(false);
      }
    })();
  }, [sys]);

  // 用户名密码登录
  async function login(username, password) {
    await client.login(username, password);
    load_user_info();
  }

  // 注销登录
  async function logout() {
    try {
      setPassed(false);
      client.set('user', undefined);
      await client.logout();
    } catch (e) {
      alert('错误', e.message, { type: 'error' });
    }
  }

  // 会话激活
  async function load_user_info() {
    try {
      let user = await client.job('B.UserInfoGet');
      client.set('user', user);
      setPassed(true);

      // 页面卸载时, SID写入cookie. 默认有效期为会话结束.因此关闭浏览器时会自动清除.
      window.addEventListener('beforeunload', function () {
        if (client.has('TOKEN')) setCookie('mp.token', client.get('TOKEN'));
      });
    } catch (e) {
      alert('错误', e.message, { type: 'error' });
    }
  }

  if (passed == null) return null;

  return (
    <SessionContext.Provider value={logout}>
      {passed ? <Watermark style={{ height: '100%' }} width={100} content={[client.get('user').名称, client.get('user').用户名]}><Outlet /></Watermark> : <Login login={login} />}
    </SessionContext.Provider>
  );
}

export default Session;